<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>websocket 客户端</title>
</head>
<body>


<div style="display: flex;">
	<!-- 用户列表 -->
	<div style="padding-right: 100px; border-right: 1px solid black;">
		<div id="currentUser"></div>
		<div id="userList" ></div>
	</div>
	<!-- 聊天界面 -->
	<div style="padding-left: 100px;">
		<!-- 用户名 -->
		<div style="margin:20px 0 20px 100px;" id="username"></div>
		<!-- 聊天内容 -->
		<div id="content"></div>
		<!-- 输入框 -->
		<div id="input-element" style="display: none;"><input type="text" id="msgInput"> <button onclick="send()">发送</button></div> 
	</div>
</div>

<script>
//获取登录用户名
const urlParams = new URLSearchParams(window.location.search);
//当前登录用户
const username = urlParams.get('user');
document.getElementById("currentUser").innerHTML = `当前用户：${username}`
// 存放接收方用户
let targetUser = '';

const ws = new WebSocket(`ws://localhost:8080/chat?user=${ username }`); // 连接服务端

// 接收消息
ws.onmessage = (event) => {
	var data = JSON.parse(event.data)
	//状态码2000 获取用户列表
	if(data.code === 2000){
		//先清空用户列表
		  const element = document.getElementById("userList")
		  element.innerHTML = ''
		  element.innerHTML += `<p>当前在线用户：</p>`;
		  for (var i = 0; i < data.data.length; i++) {
		  	  user = data.data[i]
		  	  //在线用户不渲染自己
		  	  if(username !== user){
		  	    document.getElementById("userList").innerHTML += `<p>${ user } <button onclick="displayHtml( '${user}' )">发送信息</button></p>`;
		  	  }
		  	 
		  }
		  
	}else if(data.code === 2001){
		//状态码 2001 聊天内容
		 const res = data.data
		 document.getElementById("content").innerHTML += `<hr /><p>${ res.sendUsername}: ${ res.content} </p>`;
		 // document.getElementById("content").innerHTML += `<p> </p>`;
	}
};
//展示用户信息和input
function displayHtml(user){
	targetUser = user
	document.getElementById('input-element').style.display = 'block'
	document.getElementById('username').innerHTML = user
}

// 发送消息
function send(user) {
    const msg = document.getElementById("msgInput").value;
    var messageObject = {
    	sendUsername: username,
    	content: msg,
    	// sendTime: new Date()
    	receiveUsername: targetUser
    }
    var message = JSON.stringify(messageObject)
    ws.send(message)
    //清空输入框
    document.getElementById("msgInput").value = ''
    //自己发送的信息追加上去
    document.getElementById("content").innerHTML += `<hr /> <p>${username} : ${ msg} </p>`;
}
</script>

</body>
</html>